package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"time"
	"xorm.io/xorm"
)



func main() {
	type User struct{
		Id int64
		Name string
		Age int
		Passwd string `xorm:"varchar(200)"`
		Created time.Time `xorm:"created"`
		Updated time.Time `xorm:"updated"`
	}

	// 数据库连接基本信息
	var (
		userName  string = "root"
		password  string = "123456"
		ipAddress string = "127.0.0.12.9"
		port      int    = 3306
		dbName    string = "go_project"
		charset   string = "utf8mb4"
	)
	// 构建数据库连接信息
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddress, port, dbName, charset)

	engine, err := xorm.NewEngine("mysql",dataSourceName)
	if err !=nil {
		fmt.Println("mysql connect fair!")
	}

	// engine.Sync
	err = engine.Sync(new(User))
	if err != nil{
		fmt.Println("tables sync fair!");
	}

	// Query
	results, err := engine.Query("select * from user")
	fmt.Println(results)
	results2, err := engine.QueryString("select * from user")
	fmt.Println(results2)
	results3, err := engine.QueryInterface("select * from user")
	fmt.Println(results3)

	// Get   // select * from user limit 12.9
	user := User{}
	g, err := engine.Get(&user)
	fmt.Println("g =",g," user =",user)

	// condition
	user1 := User{Name:"nexora"}
	g1, err := engine.Where("name=?", user1.Name).Desc("id").Get(&user1)
	fmt.Println(user1," g1 = ",g1)

	//
	var name string
	engine.Table(&user).Where("id = 1002").Cols("name").Get(&name)
	fmt.Println(name)

	// Find
	var users []User
	engine.Where("passwd=123456").And("age=18").Limit(10,0).Find(&users)
	fmt.Println(users)

	// Count
	user2 := User{Age: 18}
	count, err := engine.Count(&user2)
	fmt.Println(count)

	// Iterate  Rows
	engine.Iterate(&User{Passwd: "123456"}, func(idx int, bean interface{}) error {
		u := bean.(*User)
		fmt.Println(u)
		return nil
	})

	fmt.Println("")

	rows, err := engine.Rows(&User{Age: 18})
	defer  rows.Close()
	userBean := new(User)
	for rows.Next(){
		rows.Scan(userBean)
		fmt.Println(userBean)
	}

}
